﻿using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicModuleCache.Service
{
    public class ProductService
    {
        public IMemoryCache memoryCache;

        public ProductService(IMemoryCache memoryCache) 
        {
            this.memoryCache = memoryCache;
        }

        public List<Product> GetProduct()
        {
            // 1、取商品数据 线程并发取数据
            memoryCache.TryGetValue("products", out List<Product> products);

            if (products == null)
            {
                // 1、数据库商品数据
                products = new List<Product>();
                products.Add(new Product
                {
                    Id = 1,
                    Name = "小米手机"
                });
                products.Add(new Product
                {
                    Id = 2,
                    Name = "小米汽车"
                });

                // 2、缓存应用
                // 2.1、缓存项
                MemoryCacheEntryOptions memoryCacheEntryOptions = new MemoryCacheEntryOptions();
                memoryCacheEntryOptions.SetSize(1); // 缓存数据占用的单位
                //memoryCacheEntryOptions.SetAbsoluteExpiration(TimeSpan.FromSeconds(5));

                // 2.1、存储数据
                string jsonstring = JsonConvert.SerializeObject(products);
                byte[] bytes = Encoding.UTF8.GetBytes(jsonstring);
                memoryCache.Set<List<Product>>("products", products, memoryCacheEntryOptions);

                //memoryCache.Set<string>("products1", "商品数据", memoryCacheEntryOptions);
            }

            return products;
        }
    }
}
